<!-- 标准职位详情 -->
<template>
  <div class="container">
    <a-scrollbar
      style="height: calc(100vh - 216px); overflow: auto; padding: 0 10px"
      id="scrollBar"
      type="track"
    >
      <div v-for="(item, index) in data" :key="index">
        <div :id="item.collectionId">
          <div class="title-box">
            <div class="title">
              <div
                :style="{
                  marginLeft: '25px'
                }"
              >
                {{ item.collectionName }}
              </div>
              <div>
                <a-tooltip content="编辑信息">
                  <icon-font
                    :style="{
                      cursor: 'pointer'
                    }"
                    v-show="currCollectionId !== item.collectionId"
                    type="icon-edit"
                    :size="36"
                    @click="edit(item.collectionId)"
                  ></icon-font>
                </a-tooltip>
              </div>
            </div>
          </div>

          <a-form :model="item" ref="formRef" autoLabelWidth>
            <a-row :gutter="16">
              <a-col
                v-for="item2 in item.controlItems"
                :key="item2.id"
                :span="item2.span"
              >
                <FormItem
                  :name="item2.ctlCnName"
                  :componentType="item2.ctlComponentType"
                  :code="item2.ctlCode"
                  :props="item2.props"
                  v-model:values="item2.ctlValue"
                  :required="false"
                  :disabled="
                    currCollectionId !== item.collectionId ||
                    forbidEditEnum.includes(item2.ctlCode)
                  "
                  :selectOptions="item2.selectOptions"
                  :data="item2"
                ></FormItem>
              </a-col>
            </a-row>
          </a-form>

          <a-space
            v-if="currCollectionId === item.collectionId"
            class="btns"
            size="large"
          >
            <a-button @click="cancel">取消</a-button>
            <a-button type="primary" @click="save(index)">保存</a-button>
          </a-space>
        </div>
      </div>
    </a-scrollbar>
    <div v-if="scroll" class="anchor">
      <div
        class="anchor-total"
        v-for="item in data"
        :key="item.collectionId"
        @click="handleAnchor(item.collectionId)"
        :class="{ active: item.collectionId === currAnchorId }"
        :ref="(e, ind) => setAnchorRefs(e, item.collectionId)"
      >
        <div class="anchor-total-box">
          <div
            class="anchor-total-box-circle"
            :class="{ activeCircle: item.collectionId === currAnchorId }"
          ></div>
          <div class="anchor-total-box-item">
            {{ item.collectionName }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  GetPositionDefault,
  GetPositionSetting,
  PutPosition,
  PostPosition,
  GetPositionStandardDetail,
  PutPositionDetail
} from '@/apis/management/organization/positionManagement';
import { GetBusinessModalData } from '@/apis/controltotal';
import { GetHeaderSetting } from '@/apis/management/base';
import FormItem from '@/components/DynamicFormsNew/RenderingForm/FormItem/index.vue';
import { GetlistData } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import { getPositionHierarchyList } from '@/apis/management/organization/baseSetting/PositionSystem/index';
import useControlFormStore from '@/store/controlForm';
const controlFormStore = useControlFormStore();
controlFormStore.fieldNames.componentType = 'ctlComponentType';
controlFormStore.fieldNames.labelName = 'ctlCnName';
controlFormStore.fieldNames.valueName = 'ctlValue';
const route = useRoute();

// 档案id
let id = Number(route.query.id);
let ownerType = Number(route.query.ownerType);
onBeforeRouteUpdate((to) => {
  id = Number(to.query.id);
  getData();
});

let scroll = ref(); // 定义一个scroll储存scrollbar的Dom用来锚点跳转
let currAnchorId = ref(-1); // 当前选中锚点的id

onMounted(() => {
  scroll.value = document.getElementById('scrollBar');
});

let formRef = ref();

// 拼用来数据的数据
const data = reactive([
  {
    collectionId: undefined,
    collectionName: '',

    /*
controlItems
    // {
    //   controlId: undefined,
    //   mechanismId: undefined,
    //   collectionId: undefined,
    //   orderNo: undefined,
    //   value: undefined,
    //   id: undefined
    // }
*/
    controlItems: [] as any
  }
]);
// 不能修改的项 公司、部门、职位类别,职级范围
const forbidEditEnum = [
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'C8D53C139F7B44D38826E0B5A3F9F93E1'
];
let formHeader = ref();

const orginData = ref(); // 原始数据
let positionHierarchyList = ref([]); // 职位层级数据

const getData = async () => {
  try {
    const [positionDetailRes, headerSettingRes, businessModalData]: any =
      await Promise.all([
        GetPositionStandardDetail({
          id,
          ownerType
        }),
        GetHeaderSetting({
          ownerFuncType: 12,
          userId: +(localStorage.getItem('userId') as string)
        }),
        GetBusinessModalData({
          funcCode: 'SER_FUNC2B637A0650F648F5BB4C0CB49FAEDCC5'
        })
        // getPositionHierarchyList({
        //   pageNumber: 0,
        //   pageSize: -1
        // })
      ]);
    orginData.value = positionDetailRes.useTemplate.collectionModel;
    formHeader.value = [];
    const headerChildren = businessModalData.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      formHeader.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });

    let collectionIdArr: any = []; // 储存有多少不同的collectionId
    orginData.value.forEach((item: any) => {
      /* 储存唯一的collectionId */
      if (!collectionIdArr.includes(item.id)) collectionIdArr.push(item.id);
    });

    /* 每次先将数组清空再赋一个空对象然后传入唯一的collectionId */
    data.length = 0;

    collectionIdArr.forEach((item: any, index: any) => {
      data.push({
        collectionId: undefined,
        collectionName: '',
        controlItems: []
      });
      data[index].collectionId = item;
    });
    console.log('====================================orginData');
    console.log(orginData.value);
    console.log('====================================');
    // 循环赋值
    data.forEach((item1: any) => {
      orginData.value.forEach((item2: any) => {
        item2.controlModel.forEach((item3: any) => {
          let ctlCode = item3.ctlCode,
            ctlValue = item3.ctlValue.ctlValue;
          if (item1.collectionId === item2.id) {
            if (item1.collectionName === '')
              item1.collectionName = item2.cnName;
            item1.controlItems.push({
              controlId: item3.id,
              collectionId: item2.collectionId,
              orderNo: item2.orderNo,

              // 如果ctlCode是以下的值就要转为Number类型的值
              ctlValue:
                // isNaN(+ctlValue) && ctlValue !== 'undefined'
                //   ? ctlValue
                //   : ctlValue === ''
                //   ? ''
                //   : ctlValue == 'undefined'
                //   ? undefined
                //   : +ctlValue,
                isNaN(+ctlValue) ? ctlValue : +ctlValue || ctlValue,
              id: item3.ctlValue.id,
              ctlCnName: item3.ctlCnName,
              ctlCode: ctlCode,
              code: ctlCode,
              ctlComponentType: item3.ctlComponentType,
              props: JSON.parse(item3.props),
              required: item3.required,
              span: item3.span
            });
          }
        });
      });
    });

    let idaaa = 0;
    // 获取公司ID，请求部门下拉数据
    data.forEach((item: any) => {
      item.controlItems.forEach(async (ele: any) => {
        if (ele.code === 'CA8ABCC1480744557B3014C3454465A7E') {
          idaaa = ele.value;
        } else if (ele.code === 'CED44AC9966904CD1AB546D309903727C') {
          ele.selectOptions = await GetlistData({ type: 2, id: idaaa });
        } else if (ele.code === 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC') {
          const { content } = await getPositionHierarchyList({
            pageNumber: 0,
            pageSize: -1
          });
          setTimeout(() => {
            ele.selectOptions = content;
            console.log('===================selectOptions=================');
            console.log(ele.selectOptions);
            console.log('====================================');
          }, 100);
        }
      });
    });
    console.log('==================================== orginData.value ');
    console.log(data);
    console.log(positionHierarchyList.value);
    console.log('====================================');

    // data[0].controlItems.forEach(async (ele: any) => {
    //   if (ele.code === 'CED44AC9966904CD1AB546D309903727C') {
    //     ele.selectOptions = await GetlistData({ type: 2, id: idaaa });
    //     console.log(2222222222222222, ele.selectOptions);
    //   }
    // });
    currAnchorId.value = data[0].collectionId;
  } catch (error: unknown) {
    console.log(error);
  }
};

getData();

let currCollectionId = ref(0); // 储存当前选中子类的collectionId，用来编辑

const eleAnchorRefs = ref([]); // 储存锚点的refs

// 动态设置锚点的refs
const setAnchorRefs = (e, ind) => {
  eleAnchorRefs.value[ind] = e;
};
// 处理锚点数据
const handleAnchor = (id: number) => {
  currAnchorId.value = id;
  eleAnchorRefs.value[id]?.scrollIntoView({
    behavior: 'smooth'
  });
  let targetElement = document.getElementById(`${id}`);
  let targetOffset = targetElement?.offsetTop;
  // 获取包含目标元素的父级 div
  let parentDiv = document.getElementById('scrollBar'); // 将 'your-parent-div-id' 替换为实际的父级 div 的 id
  // 平滑滚动到目标位置
  parentDiv.scrollTo({
    top: targetOffset,
    behavior: 'smooth'
  });
};
// 编辑按钮
const edit = (collectionId: number | undefined) => {
  if (currCollectionId.value !== collectionId)
    currCollectionId.value = collectionId as number;
  else currCollectionId.value = 0;
};

// 编辑取消按钮
const cancel = () => {
  currCollectionId.value = 0;
};

// 保存某一部分表单
const save = async (index: number) => {
  try {
    let temp = cloneDeep(data[index].controlItems);

    const positionLibrary = {
      name: ''
    };
    temp.forEach((item: any) => {
      item.ctlValue = `${item.ctlValue}`;
      formHeader.value.forEach((item2: any) => {
        if (item2.code === item.code) item.code = item2.code;
      });
      if (item.code === 'C2818BAA63AE848AA845DA2E81ECB1843')
        positionLibrary.name = `${item.ctlValue}`;
      delete item.ctlCnName;
      delete item.ctlCode;
      delete item.ctlComponentType;
      delete item.props;
      delete item.required;
      delete item.span;
    });

    // 编辑之前先校验
    formRef.value[index].validate(async (valid: any) => {
      if (valid === undefined) {
        await PutPositionDetail({
          organizationTemplateCtlValue: temp,
          positionLibrary
        });
        currCollectionId.value = 0;
      } else {
        Message.error('请填写必填的信息！');
      }
    });
    currCollectionId.value = 0;
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style scoped lang="less">
.container {
  display: flex;
  .anchor {
    padding-left: 20px;
    display: flex;
    flex-direction: column;
    &-total {
      display: inline-block;
      text-decoration: none;
      color: #000;
      height: 36px;
      line-height: 36px;
      z-index: 9;
      &:last-child .anchor-total-box-circle::after {
        content: none; /* 移除连线样式 */
      }
      &-box {
        width: 120px;
        position: relative;
        display: flex;
        align-items: center;

        &:active,
        &:hover {
          background-color: #edeffd;
        }

        &-item {
          position: relative;
          font-weight: 700;
          text-align: left;
        }
        &-circle {
          position: relative;
          right: 10px;
          width: 10px;
          height: 10px;
          box-shadow: 0 0 0 4px #edeffd;
          border-radius: 50%;
          background-color: #ccc;

          &::after {
            position: absolute;
            content: '';
            width: 2px; /* 线条的宽度 */
            height: calc(20px); /* 线条的高度 */
            background-color: #ccc; /* 线条的颜色 */
            bottom: -24px; /* 将线条放置在圆形下面 */
            left: 50%; /* 将线条水平居中 */
            transform: translateX(-1px); /* 修正水平居中的偏移 */
          }
        }
      }
    }
  }
  .title-box {
    position: relative;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 36px;
      border-radius: 4px;
      font-weight: 700;
      margin-bottom: 10px;
      background: #edeffd;
    }
  }

  .title-box::before {
    position: absolute;
    // top: 33px;
    left: 10px;
    display: inline-block;
    height: 18px;
    top: 50%;
    transform: translateY(-50%);
    width: 10px;
    margin-right: 20px;
    border-radius: 2px;
    // transform: translateY(-50%);
    content: '';
    background-color: #165dff;
  }
  .btns {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    margin-bottom: 10px;
  }
}
.active {
  color: #165dff !important;
}

.activeCircle {
  background-color: #165dff !important;
}
</style>
